<?php

class App_Validate_DbUnique extends Zend_Validate_Abstract
{
    const NOT_UNIQUE = 'dbUniqueNotUnique';

    protected $_messageTemplates = array(
        self::NOT_UNIQUE => '%column% %value% already exists'
    );

    /**
    * @var array
    */
    protected $_messageVariables = array(
        'column'  => '_column',
    );

    /**
     * The table where to check for unique value in column
     *
     * @var Zend_Db_Table
     */
    protected $_dbTable = NULL;

    /**
     * The column name where to check for unique value
     *
     * @var string
     */
    protected $_column = '';

    public function __construct(Zend_Db_Table_Abstract $table, $column)
    {
        $this->_dbTable = $table;
        $this->_column = $column;
    }

    public function isValid($value)
    {
        $this->_setValue($value);

        $select = $this->_dbTable->select();
        $select->where($this->_dbTable->getAdapter()->quoteInto($this->_column . ' = ?', $value));
        $row = $this->_dbTable->fetchAll($select);

        if ($row->count()) {
            $this->_error();
            return false;
        }

        return true;
    }
}
